
<!--suppress ALL -->
<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="图片名称">
        <el-input v-model="image.title" placeholder="图片名称(随便填写)"/>
      </el-form-item>

      <el-form-item label="图片热度">
        <el-input-number v-model="image.sort" :min="0" :max="10000" controls-position="right" style="width: 130px"/>
      </el-form-item>

      <el-form-item label="图片状态">
        <el-select v-model="image.state" placeholder="请选择" style="width: 96px">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="图片" style="margin-top: 20px">

        <template slot-scope="scope">
          <el-upload
            class="avatar-uploader"
            :action="BASE_API+'/itservice/imageadmin'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img :alt="image.title" v-if="image.imageUrl" :src="image.imageUrl" class="avatar" style="width: 500px; height: 300px" title="点击更换">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>

        <image-cropper
          v-show="imagecropperShow"
          :width="300"
          :height="300"
          :key="imagecropperKey"
          :url="BASE_API+'/itservice/imageadmin'"
          field="file"
          @close="close"
          @crop-upload-success="cropSuccess"/>

      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="addOrEidtImage()">{{ addOrEidtArticleTitle }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import imageApi from '@/api/image'
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'

export default {
  components: { ImageCropper, PanThumb },
  data() {
    return {
      imageId: '',
      image: {
        title: '',
        imageUrl: 'https://lk-1303842271.cos.ap-beijing.myqcloud.com/guli-edu%2Favatar%2F2022%2F07%2F04%2Fb48ee5add9fe4aa99b1e04f02f721efa.jpg',
        sort: 0,
        state: 0
      },
      saveBtnDisabled: false, // 保存按钮是否禁用,
      imagecropperShow: false, // 默认上传的组件是否显示
      imagecropperKey: 0, // 上传组件key值
      BASE_API: process.env.BASE_API,// 获取dev.env.js端口号

      //状态选择下拉框
      options: [{
        value: 0,
        label: '未发布'
      }, {
        value: 1,
        label: '已发布'
      }],

      // 提交文字
      addOrEidtArticleTitle: "添加"
    }
  },

  created: function () {
    if (this.$route.params && this.$route.params.id) {
      this.addOrEidtArticleTitle = "修改"
      this.imageId = this.$route.params.id
      console.log("============路由id=============")
      console.log(this.$route.params.id)
      // 调用根据id查询方法
      this.getImageInfo()
    }
  },

  watch: {
    $route(to, from) {
      this.image={
        title: '',
        imageUrl: 'https://lk-1303842271.cos.ap-beijing.myqcloud.com/guli-edu%2Favatar%2F2022%2F07%2F04%2Fb48ee5add9fe4aa99b1e04f02f721efa.jpg',
        sort: 0,
        state: 0
      }
    }
  },

  methods: {

    //根据id获取图片信息
    getImageInfo() {
      imageApi.getImageInfoById(this.imageId)
        .then(response => {
          this.image = response.data.image
          console.log("===========获取图片===========")
          console.log(this.image)
        })
    },

    // 添加和修改图片的方法
    addOrEidtImage() {

      if (this.image.title===''){
        this.$message({
          message: "图片名不能为空",
          type: "warning"
        })
        return
      }
      //修改图片
      if (this.imageId!=="") {
        this.$confirm('确定修改图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.image.imageUrl === 'https://lk-1303842271.cos.ap-beijing.myqcloud.com/guli-edu%2Favatar%2F2022%2F07%2F04%2Fb48ee5add9fe4aa99b1e04f02f721efa.jpg') {
            this.$notify({
              message: '上传了默认图片',
              type: 'warning'
            })
          }
          imageApi.updateImage(this.image)
            .then(response => { // 修改成功
              // 提示信息
              this.$message({
                type: 'success',
                message: '修改图片成功!'
              })
              // 回到列表页面 路由跳转
              this.$router.push({path: '/image/list'})
            })
        })
      } else {
        //添加图片
        this.$confirm('确定添加图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //添加图片
          imageApi.addImage(this.image)
            .then(response => { // 添加成功
              // 提示信息
              this.$message({
                type: 'success',
                message: '添加图片成功!'
              })
              // 回到列表页面 路由跳转
              this.$router.push({path: '/image/list'})
            })
        })
      }
    },

    handleAvatarSuccess(res, file)
    {
      console.log("============上传文件=============")
      console.log("res = ", res)
      console.log("file = ", file)
      console.log("res = ", res.data.url)

      this.image.imageUrl = res.data.url
    },

    beforeAvatarUpload(file)
    {
      const isFormat = file.type === 'image/jpeg' ||
                      file.type === 'image/png' ||
                      file.type === 'image/jpg' ||
                      file.type === 'image/gif' ||
                      file.type === 'image/bmp';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isFormat) {
        this.$message.error('上传头像图片只能是 jpg/jpeg/png/bmp/gif 格式!');
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isFormat && isLt10M;
    },

    // 关闭上传弹窗
    close()
    {
      this.imagecropperShow = false
      // 解决上传完图片重新上传需要点两次，将id+1
      this.imagecropperKey += 1
    },

    // 上传成功方法
    cropSuccess(data)
    {
      // 关闭弹窗
      this.imagecropperShow = false
      // 上传之后接口返回图片地址
      this.banner.imageUrl = data.url
      // 解决上传完图片重新上传需要点两次，将id+1
      this.imagecropperKey += 1
    }
  }
}

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
